package com.kang.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 这个就是过滤的方法
     * 过滤器链
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        //HttpServletRequest   web中的
//        //ServerHttpRequest webFlux里面的  响应式里面的
//
//        ServerHttpResponse response = exchange.getResponse();
//        //用了微服务 前后端分离项目 交互数据类型一般为Json数据类型
//        //设置编码
//        response.getHeaders().set("content-type","application/json;charset=utf-8");
//        //主装业务返回值
//        Map<String,Object> hashMap = new HashMap<>();
//        hashMap.put("code", HttpStatus.UNAUTHORIZED.value()); //未授权
//        hashMap.put("mas","未授权，请先授权");
//        ObjectMapper mapper = new ObjectMapper();
//        byte[] bytes = new byte[0];
//        try {
//            //把一个map转为字节
//            bytes = mapper.writeValueAsBytes(hashMap);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
//        //获得一个字节工厂 装饰者模式
//        DataBuffer wrap = response.bufferFactory().wrap(bytes);
//        return response.writeWith(Mono.just(wrap));
        return chain.filter(exchange);
    }


    /**
     * 指定过滤器顺序的方法
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
